<template>
	<view class="message-page" :style="{ paddingTop: statusBarHeight + 'px' }">
		<!-- 消息类型切换 -->
		<view class="tab-bar">
			<view v-for="(tab, index) in tabs" :key="index" :class="['tab-item', currentTab === index ? 'active' : '']"
				@tap="switchTab(index)">
				<text class="tab-text">{{ tab }}</text>
				<!-- 未读消息数量提示 -->
				<view v-if="getUnreadCountByType(index) > 0" class="tab-unread-badge">
					{{ getUnreadCountByType(index) > 99 ? '99+' : getUnreadCountByType(index) }}
				</view>
			</view>
		</view>

		<!-- 消息列表 -->
		<scroll-view scroll-y class="message-list">
			<!-- 提醒消息 -->
			<view v-if="currentTab === 0" class="message-content">
				<!-- 好友申请提醒卡片 -->
				<view class="message-item friend-request-card" @tap="goToFriendRequests">
					<image src="/static/images/friendSp.png" mode="aspectFill" class="message-avatar"></image>
					<view class="message-info">
						<view class="message-header">
							<text class="message-title">好友申请</text>
							<text class="message-time"></text>
						</view>
						<text class="message-desc line-clamp-1">点击查看所有好友申请记录</text>
					</view>
					<view v-if="pendingFriendRequestsCount > 0" class="unread-badge">
						{{ pendingFriendRequestsCount > 99 ? '99+' : pendingFriendRequestsCount }}
					</view>
				</view>
				
				<!-- 互动消息提醒卡片 -->
				<view class="message-item interaction-card" @tap="goToRemind">
					<image src="/static/images/hudong.png" mode="aspectFill" class="message-avatar"></image>
					<view class="message-info">
						<view class="message-header">
							<text class="message-title">互动消息</text>
							<text class="message-time"></text>
						</view>
						<text class="message-desc line-clamp-1">点击查看评论、点赞等互动消息</text>
					</view>
					<view v-if="interactionUnreadCount > 0" class="unread-badge">
						{{ interactionUnreadCount > 99 ? '99+' : interactionUnreadCount }}
					</view>
				</view>
			</view>

			<!-- 好友消息 -->
			<view v-if="currentTab === 1" class="message-content">
				<view class="message-item" v-for="(item, index) in friends" :key="index"
					@tap="goToChat('friend', item)">
					<image :src="item.avatar" mode="aspectFill" class="message-avatar"></image>
					<view class="message-info">
						<view class="message-header">
							<text class="message-title">{{ item.name }}</text>
							<text class="message-time">{{ item.time }}</text>
						</view>
						<text class="message-desc line-clamp-1">{{ item.lastMessage }}</text>
					</view>
					<view v-if="item.unreadCount > 0" class="unread-badge">
						{{ item.unreadCount > 99 ? '99+' : item.unreadCount }}
					</view>
				</view>
			</view>

			<!-- 咨询消息 -->
			<view v-if="currentTab === 2" class="message-content">
				<view class="message-item" v-for="(item, index) in consultations" :key="index"
					@tap="goToChat('consultant', item)">
					<image :src="item.avatar" mode="aspectFill" class="message-avatar"></image>
					<view class="message-info">
						<view class="message-header">
							<text class="message-title">{{ item.name }}</text>
							<text class="message-time">{{ item.time }}</text>
						</view>
						<text class="message-desc line-clamp-1">{{ item.lastMessage }}</text>
					</view>
					<view v-if="item.unreadCount > 0" class="unread-badge">
						{{ item.unreadCount > 99 ? '99+' : item.unreadCount }}
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 未登录提示 -->
		<LoginPrompt :is-login="isLogin" prompt-text="请登录后查看消息" @goToLogin="goToLogin" />
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted,
		computed
	} from 'vue'
	import {
		onShow
	} from '@dcloudio/uni-app'
	import userManager from '../../common/utils/user.js'
	import systemUtils from '../../common/utils/system.js'
	import messageCenter from '../../common/utils/messagecenter.js'
	import {
		initSocket
	} from '../../common/utils/websocket.js'
	import TimeUtil from '../../common/utils/time.js'
	import LoginPrompt from '../../components/LoginPrompt.vue'
	import {
		agreeFriend,
		refuseFriend
	} from '@/api/friend.js'
	import {
		sendSocketMessage
	} from '@/common/utils/websocket.js'

	const statusBarHeight = ref(0)
	const currentTab = ref(0)
	const isLogin = ref(false)

	// 使用 messageCenter 的 chatList，通过观察者模式自动更新
	const chatList = ref([...messageCenter.chatList])
	
	// 好友申请列表
	const friendRequests = ref([])
	
	// 待处理的好友申请数量
	const pendingFriendRequestsCount = ref(0)
	
	// 互动消息未读数量
	const interactionUnreadCount = ref(0)

	// 消息类型标签
	const tabs = ['提醒', '好友', '咨询']

	// 格式化时间显示
	const formatTime = (timeStr) => {
		if (!timeStr) return ''
		// 假设接口返回的是类似"2023-10-01 12:30:45"的格式
		const date = new Date(timeStr)
		// 检查日期是否有效
		if (isNaN(date.getTime())) return ''
		
		const now = new Date()
		const diff = now - date
		
		// 如果是今天，显示时:分
		if (date.toDateString() === now.toDateString()) {
			return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
		}
		
		// 如果是昨天，显示昨天
		const yesterday = new Date(now)
		yesterday.setDate(yesterday.getDate() - 1)
		if (date.toDateString() === yesterday.toDateString()) {
			return '昨天'
		}
		
		// 如果是一周内，显示星期几
		if (diff < 7 * 24 * 60 * 60 * 1000) {
			const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
			return weekdays[date.getDay()]
		}
		
		// 其他情况显示月/日
		return `${date.getMonth() + 1}/${date.getDate()}`
	}

	// 计算属性：好友消息
	const friends = computed(() => {
		return chatList.value
			.filter(chat => chat.chatType === 'friend')
			.map(chat => ({
				id: chat.id,
				type: 'friend',
				name: chat.user.name,
				avatar: chat.user.headImg,
				lastMessage: messageCenter.getLastMessage(chat),
				time: formatTime(chat.lastTime),
				unreadCount: messageCenter.getUnreadCount(chat)
			}))
	})

	// 计算属性：咨询消息
	const consultations = computed(() => {
		return chatList.value
			.filter(chat => chat.chatType === 'consultation')
			.map(chat => ({
				id: chat.id,
				type: 'consultation',
				name: chat.user.name,
				avatar: chat.user.headImg,
				lastMessage: messageCenter.getLastMessage(chat),
				time: formatTime(chat.lastTime),
				unreadCount: messageCenter.getUnreadCount(chat)
			}))
	})

	// 创建观察者对象
	const observer = {
		update: () => {
			console.log("消息列表有更新")
			// 响应式更新：通过 ref 更新数据
			chatList.value = [...messageCenter.chatList]
			// 更新TabBar徽章
			messageCenter.setTabBarBadge()
			
			// 更新好友申请列表
			loadFriendRequests()
			
			// 更新好友申请未读数量
			calculateFriendRequestUnreadCount()
			
			// 更新互动消息未读数量
			calculateInteractionUnreadCount()
			
			console.log("更新后的聊天列表:", messageCenter.chatList)
		}
	}

	// 页面加载时获取状态栏高度并检查登录状态
	onMounted(() => {
		statusBarHeight.value = systemUtils.getStatusBarHeight()
		checkLoginStatus()

		// 添加观察者
		messageCenter.addObserver(observer)

		// 监听登录状态变化
		uni.$on('loginStatusChanged', handleLoginStatusChanged)

		// 初始化 WebSocket
		if (isLogin.value) {
			initSocket()
			// 同步聊天列表
			chatList.value = [...messageCenter.chatList]
			
			// 加载好友申请
			loadFriendRequests()
			
			// 计算好友申请未读数量
			calculateFriendRequestUnreadCount()
			
			// 计算互动消息未读数量
			calculateInteractionUnreadCount()
			
			// 调试日志
			console.log('初始化时的聊天列表:', messageCenter.chatList)
		}
	})

	// 页面显示时更新数据
	onShow(() => {
		// 检查登录状态
		checkLoginStatus()

		// 同步最新的聊天列表
		chatList.value = [...messageCenter.chatList]

		// 重新计算未读消息数量
		messageCenter.calculateUnreadCounts(false)

		// 在消息页面显示时，主动更新 TabBar 徽章
		messageCenter.setTabBarBadge()
		
		// 加载好友申请
		loadFriendRequests()
		
		// 计算好友申请未读数量
		calculateFriendRequestUnreadCount()
		
		// 计算互动消息未读数量
		calculateInteractionUnreadCount()
		
		// 调试日志
		console.log('页面显示时的聊天列表:', messageCenter.chatList)
	})

	const checkLoginStatus = () => {
		isLogin.value = userManager.checkLogin()
	}

	// 处理登录状态变化
	const handleLoginStatusChanged = (loginStatus) => {
		isLogin.value = loginStatus
		if (loginStatus) {
			initSocket()
			chatList.value = [...messageCenter.chatList]
			
			// 加载好友申请
			loadFriendRequests()
			
			// 计算好友申请未读数量
			calculateFriendRequestUnreadCount()
			
			// 计算互动消息未读数量
			calculateInteractionUnreadCount()
			
			// 调试日志
			console.log('登录状态变化时的聊天列表:', messageCenter.chatList)
		}
	}

	// 根据tab类型获取未读消息数量
	const getUnreadCountByType = (typeIndex) => {
		const typeMap = ['notification', 'friend', 'consultation']
		const type = typeMap[typeIndex]
		return messageCenter.getUnreadCountByType(type)
	}

	const switchTab = (index) => {
		currentTab.value = index
	}

	// 根据消息类型跳转到不同页面
	const goToChat = (type, item) => {
		console.log('Go to chat with', type, item)
		// 检查登录状态
		if (!userManager.checkLogin()) {
			showLoginPrompt()
			return
		}

		// 根据消息类型确定 chatType
		const chatTypeMap = {
			'notification': 'notification',
			'friend': 'friend',
			'consultant': 'consultation',
			'consultation': 'consultation'
		}
		const chatType = chatTypeMap[type] || type
		
		// 如果是提醒消息，需要进一步判断是否是好友申请相关的提醒
		if (chatType === 'notification') {
			// 检查是否是好友申请相关的提醒
			const isFriendRequestRelated = item.action === 'friend_request' || 
										  item.action === 'friend_accepted' || 
										 item.action === 'friend_rejected';
			
			if (isFriendRequestRelated) {
				// 如果是好友申请相关的提醒，跳转到好友申请页面
				goToFriendRequests();
				return;
			}
			
			// 找到对应的聊天记录并标记为已读
			const chat = messageCenter.chatList.find(c => 
				c.id === item.id && c.chatType === 'notification'
			)
			
			if (chat) {
				// 标记所有消息为已读
				chat.readNum = chat.list.length
				chat.readTime = TimeUtil.now ? TimeUtil.now() : new Date().toLocaleString()
				
				// 更新到 messageCenter（会触发未读数量重新计算和TabBar徽章更新）
				messageCenter.setReadTime(chat)
			} else {
				// 如果找不到对应的聊天记录，标记所有提醒类型的聊天为已读
				const notificationChats = messageCenter.chatList.filter(c => 
					c.chatType === 'notification'
				)
				
				notificationChats.forEach(chat => {
					chat.readNum = chat.list.length
					chat.readTime = TimeUtil.now ? TimeUtil.now() : new Date().toLocaleString()
					messageCenter.setReadTime(chat)
				})
			}
			
			// 更新TabBar徽章
			messageCenter.setTabBarBadge()
			
			// 跳转到提醒页面
			uni.navigateTo({
				url: `/pages/remind/remind`
			})
			return
		}
		
		// 其他类型消息跳转到聊天页面
		uni.navigateTo({
			url: `/pages/chat/chat?id=${item.id}&name=${encodeURIComponent(item.name)}&avatar=${encodeURIComponent(item.avatar)}&chatType=${chatType}`
		})
	}

	// 跳转到好友申请页面
	const goToFriendRequests = () => {
		// 检查登录状态
		if (!userManager.checkLogin()) {
			showLoginPrompt()
			return
		}
		
		// 清除好友申请相关的未读消息
		const notificationChats = messageCenter.chatList.filter(c => 
			c.chatType === 'notification' && 
			(c.user.action === 'friend_request' || 
			 c.user.action === 'friend_accepted' || 
			 c.user.action === 'friend_rejected')
		)
		
		notificationChats.forEach(chat => {
			// 标记所有消息为已读
			chat.readNum = chat.list.length
			chat.readTime = TimeUtil.now ? TimeUtil.now() : new Date().toLocaleString()
			messageCenter.setReadTime(chat)
		})
		
		// 更新TabBar徽章
		messageCenter.setTabBarBadge()
		
		// 重新计算好友申请未读数量
		calculateFriendRequestUnreadCount()
		
		// 重新计算互动消息未读数量
		calculateInteractionUnreadCount()
		
		// 跳转到好友申请页面
		uni.navigateTo({
			url: '/pages/friend-requests/friend-requests'
		})
	}
	
	// 跳转到互动消息页面
	const goToRemind = () => {
		// 检查登录状态
		if (!userManager.checkLogin()) {
			showLoginPrompt()
			return
		}
		
		// 清除互动消息相关的未读消息
		const notificationChats = messageCenter.chatList.filter(c => 
			c.chatType === 'notification' && 
			// 如果没有action字段或者action字段不是好友申请相关的，则认为是互动消息
			(!c.user.action || 
			 !(c.user.action === 'friend_request' || 
			   c.user.action === 'friend_accepted' || 
			   c.user.action === 'friend_rejected'))
		)
		
		notificationChats.forEach(chat => {
			// 标记所有消息为已读
			chat.readNum = chat.list.length
			chat.readTime = TimeUtil.now ? TimeUtil.now() : new Date().toLocaleString()
			messageCenter.setReadTime(chat)
		})
		
		// 更新TabBar徽章
		messageCenter.setTabBarBadge()
		
		// 重新计算好友申请未读数量
		calculateFriendRequestUnreadCount()
		
		// 重新计算互动消息未读数量
		calculateInteractionUnreadCount()
		
		// 跳转到提醒页面
		uni.navigateTo({
			url: '/pages/remind/remind'
		})
	}

	const showLoginPrompt = () => {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		})
		setTimeout(() => {
			uni.switchTab({
				url: '/pages/mine/mine'
			})
		}, 1000)
	}

	const goToLogin = () => {
		uni.switchTab({
			url: '/pages/mine/mine'
		})
	}

	// 加载好友申请
	const loadFriendRequests = () => {
		// 从本地存储获取好友申请（模拟）
		const requests = uni.getStorageSync('receivedFriendRequests') || []
		friendRequests.value = requests
		
		// 计算待处理的好友申请数量
		pendingFriendRequestsCount.value = requests.filter(req => req.status === 'pending').length
	}
	
	// 计算互动消息未读数量
	const calculateInteractionUnreadCount = () => {
		// 计算所有非好友申请相关的提醒消息未读数量
		const notificationChats = messageCenter.chatList.filter(chat => 
			chat.chatType === 'notification' && 
			chat.user && 
			// 互动消息的判断逻辑：
			// 1. 如果有action字段，且不是好友申请相关的action，则是互动消息
			// 2. 如果没有action字段，则默认是互动消息（因为好友申请消息应该有action字段）
			(!chat.user.action || 
			 !(chat.user.action === 'friend_request' || 
			   chat.user.action === 'friend_accepted' || 
			   chat.user.action === 'friend_rejected'))
		)
		
		let count = 0
		notificationChats.forEach(chat => {
			// 确保 readNum 存在，默认为 0
			const readNum = chat.readNum || 0
			const unreadCount = chat.list.length - readNum
			if (unreadCount > 0) {
				count += unreadCount
			}
		})
		
		interactionUnreadCount.value = count
		console.log('互动消息未读数量计算结果:', count, '相关聊天:', notificationChats)
	}

	// 计算好友申请未读数量
	const calculateFriendRequestUnreadCount = () => {
		// 计算所有好友申请相关的提醒消息未读数量
		const friendRequestChats = messageCenter.chatList.filter(chat => 
			chat.chatType === 'notification' && 
			chat.user && 
			// 好友申请消息必须有action字段，且action字段是好友申请相关的
			(chat.user.action === 'friend_request' || 
			 chat.user.action === 'friend_accepted' || 
			 chat.user.action === 'friend_rejected')
		)
		
		let count = 0
		friendRequestChats.forEach(chat => {
			// 确保 readNum 存在，默认为 0
			const readNum = chat.readNum || 0
			const unreadCount = chat.list.length - readNum
			if (unreadCount > 0) {
				count += unreadCount
			}
		})
		
		pendingFriendRequestsCount.value = count
		console.log('好友申请未读数量计算结果:', count, '相关聊天:', friendRequestChats)
	}
</script>

<style scoped>
	@import url('message.css');
	
	.friend-request-item {
		flex-direction: column;
		align-items: flex-start;
	}
	
	.friend-request-card {
		background-color: #FFF3E0;
	}
	
	.friend-request-actions {
		display: flex;
		flex-direction: row;
		gap: 20rpx;
		margin-top: 20rpx;
		align-self: flex-end;
	}
	
	.action-btn {
		padding: 10rpx 20rpx;
		font-size: 24rpx;
		border-radius: 10rpx;
	}
	
	.accept-btn {
		background-color: #89CFF0;
		color: white;
	}
	
	.reject-btn {
		background-color: #FF3B30;
		color: white;
	}
</style>